<template>
  <view class="search-box-container">
    <!-- 搜索框 -->
    <view class="search-box">
      <uni-search-bar @confirm="search" :focus="true" v-model="searchValue" @focus="focus" @input="input" :radius="100" cancelButton="false"></uni-search-bar>
    </view>
    <!-- 建议列表 -->
    <template v-if="searchList.length !== 0">
      <view class="sugg-list">
        <view class="sugg-item" v-for="(sugg, index) in searchList" :key="index" @click="gotoDetail(sugg.goods_id)">
          <view class="goods-name">{{ sugg.goods_name }}</view>
          <uni-icons type="arrowright" size="16"></uni-icons>
        </view>
      </view>
    </template>
    <!-- 搜索历史 -->
    <template v-else>
      <view class="history-box">
        <view class="history-title">
          <text>搜索历史</text>
          <uni-icons :type="delIconStatus" size="20" @click="clearHistory"></uni-icons>
        </view>
        <view class="history-list">
          <view class="history-item" v-for="item in historys" :key="index">
            <uni-tag :text="item" :type="tagStatus" @click="tagToggle(item)"></uni-tag>
            <uni-icons v-if="delIconStatus === 'trash-filled'" class="icon-close" type="close" size="14" color="#aa0000"></uni-icons>
          </view>
        </view>
      </view>
    </template>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchValue: '', // 输入框最终结果
      timer: null, // 定时器
      searchList: [], // 联想数据
      historyList: [], // 手动模拟搜索历史
      tagStatus: 'default',
      delIconStatus: 'trash'
    };
  },
  computed: {
    historys() {
      return [...this.historyList].reverse();
    }
  },
  onLoad() {
    // 在页面加载时同步加载本地缓存中的搜索历史
    this.historyList = JSON.parse(uni.getStorageSync('searchHistory') || '[]');
    this.clickStatus();
  },
  methods: {
    search(e) {
      // console.log(e);
      uni.navigateTo({
        url: '/subpkg/goods_list/goods_list?query=' + e
      });
    },
    focus() {
      this.clickStatus();
    },
    input(e) {
      // console.log(e);
      // 防抖
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.searchValue = e;
        this.getSearchList();
      }, 500);
    },
    // 待删除状态
    delStatus() {
      this.tagStatus = 'error';
      this.delIconStatus = 'trash-filled';
    },
    // 待点击状态
    clickStatus() {
      this.tagStatus = 'default';
      this.delIconStatus = 'trash';
    },
    // 获取建议数据列表
    async getSearchList() {
      if (this.searchValue === '') {
        // 如果之前列表有数据当searchValue没值时将其置空
        this.searchList = [];
        return;
      }
      const { data: res } = await uni.$http.get('/goods/qsearch', { query: this.searchValue });
      // console.log(res);
      if (res.meta.status !== 200) {
        //请求失败时
        return uni.$showMsg();
      }
      // console.log(res);
      this.searchList = res.message; // 数据请求成功
      // 当搜索建议成功后 调用 saveSearchHistory 保存关键词
      this.saveSearchHistory();
    },

    // 保存搜索关键词
    saveSearchHistory() {
      // this.historyList.push(this.kw)
      // 1、将数组转换为Set集合
      let set = new Set(this.historyList);
      // 2、先将原集合中的相同搜索值给删除
      set.delete(this.searchValue);
      // 3、再添加新搜索词 保证搜索词的唯一性
      set.add(this.searchValue);
      // 4、将去重后的set集合转换为数组
      this.historyList = Array.from(set);
      // 5、调用 uni.setStorageSync 同步的将搜素历史列表持久化存储在缓存中
      uni.setStorageSync('searchHistory', JSON.stringify(this.historyList));
    },

    // 点击 sugg-item 跳转商品详情
    gotoDetail(id) {
      // console.log(id);
      uni.navigateTo({
        url: '/subpkg/goods_detail/goods_detail?goods_id=' + id
      });
    },

    // 清除搜索历史
    clearHistory() {
      this.delIconStatus = this.delIconStatus === 'trash' ? 'trash-filled' : 'trash';
      this.tagStatus = this.tagStatus === 'default' ? 'error' : 'default';
    },
    // 点击 tagToggle 后
    tagToggle(seaHistory) {
      if (this.tagStatus === 'error') {
        let historyStorage = this.historyList;
        let historySet = new Set(historyStorage);
        historySet.delete(item);
        uni.setStorageSync('searchHistory', JSON.stringify(Array.from(historySet)));
        this.historyList = JSON.parse(uni.getStorageSync('searchHistory') || '[]');
        return;
      }
      uni.navigateTo({
        url: '/subpkg/goods_list/goods_list?query=' + seaHistory
      });
    }
  }
};
</script>

<style lang="scss">
// .search-box-container{
//   height: 1200px;
// }
.search-box {
  position: sticky;
  top: 0;
  z-index: 999;
}
.sugg-list {
  padding: 0 5px;
  .sugg-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12px;
    padding: 13px 0;
    border-bottom: 1px solid #efefef;
    .goods-name {
      // 文字不允许换行
      white-space: nowrap;
      // 溢出部分隐藏
      overflow: hidden;
      // 文本溢出后，使用 ... 代替
      text-overflow: ellipsis;
      margin-right: 3px;
    }
  }
}
.history-box {
  padding: 0 5px;
  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #efefef;
    height: 40px;
    font-size: 13px;
  }
  .history-list {
    display: flex;
    flex-wrap: wrap;
    .history-item {
      padding: 5px 5px;
      position: relative;
      .icon-close {
        position: absolute;
        top: -4px;
        right: 0;
      }
    }
  }
}
</style>
